// controllers/todoController.js
const todoModel = require('../models/todoModel');

class TodoController {
  async getAllTodos(req, res) {
    try {
      const { completed } = req.query;
      const filter = {};
      
      if (completed !== undefined) {
        filter.completed = completed === 'true';
      }
      
      const todos = await todoModel.getAllTodos(filter);
      return res.status(200).json(todos);
    } catch (error) {
      console.error('获取待办事项失败:', error);
      return res.status(500).json({ error: '获取待办事项失败' });
    }
  }
  
  async createTodo(req, res) {
  // 请自行实现，可参考AI
  }
  
  async deleteTodo(req, res) {
    try {
      const id = Number(req.params.id);
      
      await todoModel.deleteTodo(id);
      return res.sendStatus(204);
    } catch (error) {
      if (error.message === '待办事项未找到') {
        return res.status(404).json({ error: '待办事项未找到' });
      }
      
      console.error('删除待办事项失败:', error);
      return res.status(500).json({ error: '删除待办事项失败' });
    }
  }
  
  async updateTodoStatus(req, res) {
    try {
      const id = Number(req.params.id);
      const { completed } = req.body;
      
      if (completed === undefined) {
        return res.status(400).json({ error: '完成状态是必需的' });
      }
      
      const updatedTodo = await todoModel.updateTodoStatus(id, completed);
      return res.status(200).json(updatedTodo);
    } catch (error) {
      if (error.message === '待办事项未找到') {
        return res.status(404).json({ error: '待办事项未找到' });
      }
      
      console.error('更新待办事项状态失败:', error);
      return res.status(500).json({ error: '更新待办事项状态失败' });
    }
  }
  
  async getStudentInfo(req, res) {
    const studentInfo = {
      name: process.env.STUDENT_NAME || "未设置姓名",
      id: process.env.STUDENT_ID || "未设置学号",
      lab: "MVC架构重构实验",
      timestamp: new Date().toISOString()
    };
    
    return res.status(200).json(studentInfo);
  }
}

module.exports = new TodoController();